<template>
    <div class="page" v-loading="loading">
        <div class="page-header flex-row flex-item">
            <div class="flex1"></div>
            <el-button v-if="unBindMsg" type="warning" size="mini" @click="showUnBind">存在未绑定分类</el-button>
            <el-button v-if="$auth['operation_deviceType_add']" slot="append" type="primary" icon="el-icon-plus" size="mini" @click="openDialog({pid: 0})">增加一级分类</el-button>
        </div>
        <tz-table
                :data="loadData"
                :pagination="false"
                row-key="id"
                size="mini"
                ref="deviceTable">
            <el-table-column
                    prop="keyName"
                    label="设备分类名称">
            </el-table-column>
            <el-table-column
                    prop="key"
                    label="key"
                    :formatter="(row) => {
                     return ['nullnull', 'nullnullnull'].includes(row.key)? '未分类数据' : row.key
                   }">
            </el-table-column>
            <el-table-column
                    prop="createTime"
                    label="创建时间"
                    :formatter="(row) => {
                     return row.createTime ? moment(row.createTime).format('YYYY-MM-DD HH:mm:ss') : '-'
                   }">
            </el-table-column>
            <el-table-column
                    label="操作">
                <template slot-scope="scope">
                    <el-button v-if="$auth['operation_deviceType_rename']" size="mini" type="text" @click="openDialog(scope.row)">重命名</el-button>
                    <el-button v-if="$auth['operation_deviceType_delete']" size="mini" type="text" @click="deleteDeviceType(scope.row)">删除</el-button>
                    <el-button v-if="!+scope.row.pid && $auth['operation_deviceType_addChild']" size="mini" type="text" @click="openDialog({pid: scope.row.id, pkey: scope.row.key})">增加子类</el-button>
                </template>
            </el-table-column>
        </tz-table>
        <el-dialog
                :title="`${formData.id ? '修改' : '增加'}${[0, '0'].includes(formData.pid) ? '一级' : '子级'}分类`"
                width="500px"
                @open="reset"
                :visible.sync="dialogVisible">
            <el-form :model="formData" ref="deviceForm" :rules="rules" label-width="90px">
                <el-form-item label="关联key值" prop="key">
                    <el-select v-if="!formData.id" size="small" v-model="formData.key" style="width: 100%" placeholder="请选择">
                        <el-option
                                v-for="item in deviceKeyList"
                                :key="item.key"
                                :label="item.name"
                                :value="item.key">
                        </el-option>
                    </el-select>
                    <div v-else style="color: #cccccc; border: 1px solid #e0e0e0; padding: 0 15px; height: 32px; line-height: 32px; box-sizing: border-box; border-radius: 4px">
                        {{['nullnull', 'nullnullnull'].includes(formData.key) ? '未分类设备' : formData.key}}
                    </div>
                </el-form-item>
                <el-form-item label="类型名称" prop="keyName">
                    <el-input size="small" maxlength="20" v-model="formData.keyName" placeholder="请输入"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="saveForm">确 定</el-button>
              </span>
        </el-dialog>
    </div>
</template>

<script>
import moment from 'moment'
export default {
  name: 'deviceList',
  data() {
    return {
      loading: false,
      dialogVisible: false,
      moment,
      filterData: {
        network: 'JZW',
        realName: '',
      },
      formData: {
        id: '',
        pid: 0,
        key: '',
        keyName: ''
      },
      rules: {
        keyName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        key: [
          { required: true, message: '请选择绑定的key', trigger: 'change' }
        ]
      },
      deviceKeyList: [],
      unBindMsg: ''
    }
  },
  mounted() {
    this.getUnBindDeviceType()
  },
  methods: {
    showUnBind() {
      // this.$alert(this.unBindMsg, '内容').catch(err => {
      this.$alert(this.unBindMsg, '内容').catch(() => {
        console.log('取消')
      })
    },
    getUnBindDeviceType() {
      this.unBindMsg = ''
      this.$http('/device/getUnBindDeviceType').then(res => {
        const { deviceTypeOne, deviceTypeTwo } = res
        const msg1 = deviceTypeOne.join(',')
        const msg2 = deviceTypeTwo.join(',')
        if (deviceTypeOne?.length || deviceTypeTwo?.length) {
          this.unBindMsg = `一级分类：${msg1 || '无'}，二级分类：${msg2 || '无'}`
        }
        console.log(this.unBindMsg)
      }).catch(err => {
        console.log(err.msg || '获取未绑定数据统计失败')
      })

    },
    saveForm() {
      this.$refs.deviceForm.validate((valid) => {
        if (valid) {
          this.saveDeviceType()
        }
      })
    },
    saveDeviceType() {
      this.loading = true
      const { id } = this.formData
      // this.$http.post(`/device/${id ? 'updateDeviceType' : 'addDeviceType'}`, this.formData).then(res => {
      this.$http.post(`/device/${id ? 'updateDeviceType' : 'addDeviceType'}`, this.formData).then(() => {
        this.$TZmessage.success(`${id ? '编辑' : '添加'}分类成功`)
        this.dialogVisible = false
        this.refresh()
      }).catch(err => {
        this.$TZmessage.error(err.msg || `${id ? '编辑' : '添加'}分类失败`)
      }).finally(() => {
        this.loading = false
      })
    },
    deleteDeviceType({id, keyName}){
      this.$confirm(`是否删除分类：${keyName}？`).then(() => {
        this.loading = true
        this.$http.delete(`/device/deleteDeviceType/${id}`).then(() => {
          this.$TZmessage.success('删除成功')
        }).catch(err => {
          this.$TZmessage.error(err.msg || '删除分类失败')
        }).finally(() => {
          this.refresh()
          this.loading = false
        })
      }).catch(() => {
        console.log('取消操作')
      })
    },
    openDialog(item) {
      const {key, keyName, id, pid, pkey} = item
      this.formData = {
        key, keyName, id, pid, pkey
      }
      console.log(this.formData)
      this.dialogVisible = true
      let url = '/device/getDeviceTypeOne'
      let params = {}
      if (+pid !== 0) {
        // 查询二级分类
        url = '/device/getDeviceTypeTwo'
        params = {
          key: pkey,
          pid
        }
      }
      // 编辑的时候无需加载待选列表，因为禁用的
      if (!id) {
        this.$http(url, { params }).then(res => {
          this.deviceKeyList = (res || []).map(key => {
            return {
              key,
              name: ['nullnull', 'nullnullnull'].includes(key) ? '未分类设备' : key
            }
          })
        }).catch(err => {
          this.$TZmessage.error(err.msg || '获取分类列表失败')
        })
      }
    },
    reset() {
      this.$refs.deviceForm?.resetFields()
    },
    refresh() {
      this.$refs.deviceTable.refresh(true)
    },
    loadData() {
      return this.$http('/device/getDeviceTypeList').then(res => {
        return {
          data: res
        }
      }).catch(err => {
        this.$TZmessage.error(err.msg || '获取列表数据失败')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
    .page {
    }
</style>